package com.cj.common.utils;

import cn.hutool.core.util.IdUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件上传工具类
 *
 * @author das
 */
public class FileUploadUtils {

    public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    public static File getFilePath(MultipartFile file, String path, boolean flag) {
        String fileDir = StringUtils.isEmpty(path) ? "upload" : path;
        String resourcePath = "/home/gisadmin/uploadPath";
        String originalFilename = file.getOriginalFilename();
        String uuid = IdUtil.simpleUUID();
        String fileName = null;
        if (flag) {
            String dateFilePrefix = DateUtil.getDateFilePrefix();
            fileName = dateFilePrefix + File.separator + uuid;
            fileName = FilenameUtils.normalize(fileName);
        } else {
            fileName = FilenameUtils.getBaseName(originalFilename);
        }
        Path filePaths = Paths.get(resourcePath, fileDir, fileName);
        File filePath = filePaths.toFile();
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
        }
        return filePath;
    }
}
